﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
using LuctecWS.DAL;
using LuctecWS.Aspect;

namespace LuctecWS.Core
{
    [DataContract]
    public class EmailList : Base
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public bool? Active { get; set; }

        [LogException]
        public EmailList Save()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                if (Id == 0)
                {
                    var emailList = new LuctecWS.DAL.emaillist() { Active = this.Active, Name = this.Name, Id = this.Id };

                    context.AddObject("emaillist", emailList);
                }
                else
                {
                    var emailList = context.emaillist.First(el => el.Id == Id);

                    emailList.Name = Name;
                    emailList.Active = Active;
                }

                context.SaveChanges();

                if(Id == 0)
                    return AdaptDBCore(context.emaillist.ToList().Last());
                else
                    return AdaptDBCore(context.emaillist.ToList().First(el => el.Id == Id));
            }
        }

        [LogException]
        public static List<EmailList> GetEmailLists()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                var dbEmailLists = context.emaillist.ToList();

                return AdaptDBCore(dbEmailLists);
            }
        }

        [LogException]
        private static List<EmailList> AdaptDBCore(List<emaillist> dbEmailLists)
        {
            List<EmailList> emailLists = new List<EmailList>();

            if (dbEmailLists != null)
            {
                foreach (var dbEmailList in dbEmailLists)
                {
                    EmailList emailList = AdaptDBCore(dbEmailList);

                    if (emailList != null)
                        emailLists.Add(emailList);
                }
            }

            return emailLists;
        }

        [LogException]
        private static EmailList AdaptDBCore(emaillist dbEmailList)
        {
            if (dbEmailList != null)
                return new EmailList() { Active = dbEmailList.Active, Id = dbEmailList.Id, Name = dbEmailList.Name };

            return null;
        }
    }
}